<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\MemberService;
use app\admin\model\School;
use app\admin\model\Departments;
use app\admin\model\Clss;
use app\admin\model\Professional;
use app\admin\model\Grade;

/**
 * 会员管理-控制器
 * @author 牧羊人
 * @since 2020/11/20
 * Class Member
 * @package app\admin\controller
 */
class Member extends Backend
{
    /**
     * 初始化
     * @author 牧羊人
     * @since 2020/11/20
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\admin\model\Member();
        $this->service = new MemberService();
    }

    /**
     * 获取用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function getUserInfo()
    {
        $result = $this->service->getUserInfo($this->userId);
        return $this->jsonReturn($result);
    }

    /**
     * 更新个人资料
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function updateUserInfo()
    {
        $result = $this->service->updateUserInfo($this->userId);
        return $this->jsonReturn($result);
    }

    /**
     * 获取学员列表
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getMemberList()
    {
        $result = $this->service->getMemberList();
        return $this->jsonReturn($result);
    }

    /**
     * 导入Excel
     * @author 牧羊人
     * @since 2021/5/24
     */
    public function importExcel()
    {
        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', '', $error);
        if (!$result) {
            return $this->jsonReturn(message($error, false));
        }
        // 文件路径
        $filePath = UPLOAD_TEMP_PATH . $result;
        if (!file_exists($filePath)) {
            return $this->jsonReturn(message("文件不存在", false));
        }
        // 读取文件
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetCount = $objPHPExcel->getSheetCount(); //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow(); //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        // 计数器
        $totalNum = 0;
        // 循环读取行数据
        for ($row = 2; $row <= $rowCount; $row++) {
            // 获取列值
            $dataArr = array();
            // 登录账号
            $dataArr['username'] = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();
            $dataArr['password'] = get_password('123456' . $dataArr['username']); //默认密码123456
            // 姓名
            $dataArr['realname'] = $objPHPExcel->getActiveSheet()->getCell("B" . $row)->getValue();
            // 性别
            $dataArr['gender'] = $objPHPExcel->getActiveSheet()->getCell("C" . $row)->getValue()=='男'?1:2;
            // 角色
            $dataArr['type'] = $objPHPExcel->getActiveSheet()->getCell("D" . $row)->getValue()=='学生'?1:0;
            // 学籍号
            $dataArr['roll'] = $objPHPExcel->getActiveSheet()->getCell("E" . $row)->getValue();
            // 身份证号
            $dataArr['idcard'] = $objPHPExcel->getActiveSheet()->getCell("F" . $row)->getValue();
            // 手机号
            $dataArr['mobile'] = $objPHPExcel->getActiveSheet()->getCell("G" . $row)->getValue();

            $school = new School();
            $sname = $objPHPExcel->getActiveSheet()->getCell("M" . $row)->getValue();
            $dataArr['organization'] = $school->where(['name'=>trim($sname),'mark'=>1])->value('id');
            // 年级
            $grade = new Grade();
            $gname = $objPHPExcel->getActiveSheet()->getCell("H" . $row)->getValue();
            $dataArr['grade'] = $grade->where(['organization'=>$dataArr['organization'],'name'=>trim($gname),'mark'=>1])->value('id');
            // 班级
            $class = new Clss();
            $cname = $objPHPExcel->getActiveSheet()->getCell("I" . $row)->getValue();
            $dataArr['class'] = $class->where(['name'=>trim($cname),'mark'=>1])->value('id');
            //院系
            $departments = new Departments();
            $dname = $objPHPExcel->getActiveSheet()->getCell("K" . $row)->getValue();
            $dataArr['superior'] = $departments->where(['name'=>trim($dname),'organization'=>$dataArr['organization'],'mark'=>1])->value('id');
            //专业
            $professional = new Professional();
            $pname = $objPHPExcel->getActiveSheet()->getCell("J" . $row)->getValue();
            $dataArr['professional'] = $professional->where(['superior'=>$dataArr['superior'],'name'=>trim($pname),'mark'=>1])->value('id');
            

            //院系类型
            //$dataArr['type'] = $grade->where('name',trim($dname))->value('id');

            
            
            // 状态
            $dataArr['status'] = 1;//默认正常

            $ids = $this->model->where(['roll'=>$dataArr['roll'],'mark'=>1])->value('id');
            if ($ids) {
               $dataArr['id'] = $ids;
            }
            // 插入数据
            $memberModel = new \app\admin\model\Member();
            if ($dataArr['username']) {
                $result = $memberModel->edit($dataArr);
                if ($result) {
                    $totalNum++;
                }
            }
            
        }
        return $this->jsonReturn(message("本次共导入{$totalNum}条数据", true));
    }

    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @since 2021/3/25
     * @author 牧羊人
     */
    public function exportExcel()
    {
        // 参数
        $param = request()->param();
        // 查询条件
        $map = [];

        // 学校
        $organization = getter($param, "organization");
        if ($organization) {
            $map[] = ['organization', '=', $organization];
        }

        // 院系
        $superior = getter($param, "superior");
        if ($superior) {
            $map[] = ['superior', '=', $superior];
        }

        // 年级
        $grade = getter($param, "grade");
        if ($grade) {
            $map[] = ['grade', '=', $grade];
        }

        // 专业
        $professional = getter($param, "professional");
        if ($professional) {
            $map[] = ['professional', '=', $professional];
        }

        // 班级
        $class = getter($param, "class");
        
        if ($class) {
            $map[] = ['class', '=', $class];
            // $str = '"'.$class.'"';
            // $map[] = ['features', 'like','%'.$str.'%'];
        }
        // 是否体育院系
        // $stype = getter($param, "stype");
        // if ($stype==1) {
            // // if ($class) {
                // // $map[] = ['class', '=', $class];
            // // }
        // }else{
            // if ($class) {
                // $str = '"'.$class.'"';
                // $map[] = ['features', 'like','%'.$str.'%'];
            // }
            
        // }

        // 性别
        $gender = getter($param, "gender");
        if ($gender) {
            $map[] = ['gender', '=', $gender];
        }

        $realname = getter($param, "realname");
        if ($realname) {
            $map[] = ['realname', 'like','%'.$realname.'%'];
        }

        $roll = getter($param, "roll");
        if ($roll) {
            $map[] = ['roll', 'like','%'.$roll.'%'];
        }

        $avatar = getter($param, "avatar");
        if ($avatar) {
            if ($avatar==1) {
                $map[] = ['avatar', '<>',''];
            }
            if ($avatar==2) {
                $map[] = ['avatar', '=',''];
            }
            
        }
        $map[] = ['mark', "=", 1];
        // 获取导出的数据源
        $list = $this->model->where($map)->select()->toArray();

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '登录账号')
            ->setCellValue('B1', '姓名')
            ->setCellValue('C1', '性别')
            ->setCellValue('D1', '角色')
            ->setCellValue('E1', '学籍号')
            ->setCellValue('F1', '身份证号')
            ->setCellValue('G1', '手机号')
            ->setCellValue('H1', '年级')
            ->setCellValue('I1', '班级')
            ->setCellValue('J1', '专业')
            ->setCellValue('K1', '院系')
            ->setCellValue('L1', '院系类型')
            ->setCellValue('M1', '所属组织')
            ->setCellValue('N1', '状态');
        // 设置表格头水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('L1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('M1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('N1')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //设置列水平居中
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('L')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('M')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('N')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        // 设置单元格宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('H')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('K')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('L')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('M')->setWidth(10);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('N')->setWidth(10);
        // 循环刚取出来的数组，将数据逐一添加到excel表格。
        $school = new School();
        $departments = new Departments();
        $grade = new Grade();
        $class = new Clss();
        $professional = new Professional();
        for ($i = 0; $i < count($list); $i++) {
            
            
            $organization = $school->where('id',$list[$i]['organization'])->value('name');
            $superior = $departments->where('id',$list[$i]['superior'])->value('name');
            $grade_name = $grade->where('id',$list[$i]['grade'])->value('name');
            $class_name = $grade->where('id',$list[$i]['class'])->value('name');
            $professional_name = $grade->where('id',$list[$i]['professional'])->value('name');

            $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 2), $list[$i]['username']);// 登录账户
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 2), $list[$i]['realname']);// 姓名
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 2), $list[$i]['gender']==1?'男':'女');// 性别
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 2), $list[$i]['type']==1?'学生':'');// 角色
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 2), $list[$i]['roll']);// 学籍号
            $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 2), $list[$i]['idcard']);// 身份证号
            $objPHPExcel->getActiveSheet()->setCellValue('G' . ($i + 2), $list[$i]['mobile']);// 手机号
            $objPHPExcel->getActiveSheet()->setCellValue('H' . ($i + 2), $grade_name);// 年级
            $objPHPExcel->getActiveSheet()->setCellValue('I' . ($i + 2), $class_name);// 班级
            $objPHPExcel->getActiveSheet()->setCellValue('J' . ($i + 2), $professional_name);// 专业
            $objPHPExcel->getActiveSheet()->setCellValue('K' . ($i + 2), $superior);// 院系
            $objPHPExcel->getActiveSheet()->setCellValue('L' . ($i + 2), '自然院系');// 院系类型
            $objPHPExcel->getActiveSheet()->setCellValue('M' . ($i + 2), $organization);// 组织
            $objPHPExcel->getActiveSheet()->setCellValue('N' . ($i + 2), $list[$i]['status']==1 ? "正常" : "停用");// 状态
        }
        // 设置保存的Excel表格名称
        $filename = '学生管理_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $objPHPExcel->getActiveSheet()->setTitle('学生管理');

        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        try {
            // 保存文件
            $objWriter->save(UPLOAD_TEMP_PATH . "/" . $filename);
        } catch (Exception $e) {
            echo "文件保存失败：" . $e->getMessage();
        }
        return download(UPLOAD_TEMP_PATH . "/" . $filename, $filename);
        // 文件地址
//        $filePath = get_image_url('/uploads'.str_replace(ATTACHMENT_PATH, "", UPLOAD_TEMP_PATH . "/" . $filename));
//        return $this->jsonReturn(message("操作成功", true, $filePath));
    }
}